'use strict';

import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import * as actions from '../../actions/zhekou_limit_step1';
import { Button,Step,Breadcrumb,Form,Field,Search,DatePicker,Input } from 'qnui';
import { Row, Col } from 'qnui/lib/grid';
import ZhekouTags from 'components/zhekou-tags/index';
import SystemDialog from 'components/system-dialog/index';
import './index.scss';
const FormItem = Form.Item;
class ZhekouLimitStep1 extends React.Component {

  constructor(props) {
    super(props);
    this.field = new Field(this, {
			scrollToFirstError:true,
			onChange: (name, value) => {
				if(name!="tagName"){
					this.setState({overlayVisible:false});
				}
			}
	 });
	 this.dispatch = this.props.dispatch;
    this.state = {
			overlayVisible:false,
            value: null,
			search:"",
			hasTag:false,
			isSelectTag:false,
			refreshDialog:false,
        };
  }
	componentWillReceiveProps(nextProps){
		if(nextProps.zhekou_limit_step1.activityId){
			nextProps.history.push({pathname:'/zhekou_limit_step2',state:{activityId:nextProps.zhekou_limit_step1.activityId}});
		}
	}
   componentDidMount(){
		if(this.props.location.state && this.props.location.state.createNew=="true")
	  	{
			this.props.dispatch(actions.createNew());
		}
   }
  onVisibleChange = (visible) => {
      this.setState({
          overlayVisible:visible,
			isSelectTag:false
      });
  }
	setTag(tagName){
		this.setState({isSelectTag:true});
		this.field.setValues({"tagName":tagName});
	}
	searchResult(hasTag,isPrefect){
		this.setState({"hasTag":hasTag,"isPrefect":isPrefect});
	}
	checkTag(rule,tagName,callback){
		this.setState({"search":tagName});
		if(this.state.isSelectTag){
			callback()
		}else{
			callback("请您从列表中选择标签！不可输入后直接提交")
		}
	}
	checkEndDate(rule,date,callback){
		if(!date){
			callback('必须有一个结束时间');
		}
		if (date && Date.parse(date) < Date.parse(this.field.getValue('startTime'))) {
            callback('结束时间必须晚于开始时间！');
        } 
		if (date && Date.parse(date) < Date.parse(new Date())) {
            callback('结束时间必须晚于当前系统时间！');
        } 
		{
            callback();
        }
	}
	handleSubmit(e) {
        e.preventDefault();
        this.field.validate((errors, values) => {
         if (errors) {
                return;
            }
			if(parseInt(window.info.deadline_time) < Date.parse(values.endTime)/1000){
				//截至时间不能晚于订购时间，请重新设置
				this.setState({"orderDialog":true});
				return;
			}
         if(parseInt(window.info.timestemp)+1800 < Date.parse(new Date())/1000){
    			// 操作授权超过半小时，请重新授权
    			this.setState({"refreshDialog":true});
    			return;
    		}
			values.endTime = Date.parse(values.endTime)/1000;
			values.startTime = Date.parse(values.startTime)/1000;
			this.props.dispatch(actions.createZhekou(values));
        });
    }
	onCloseSystemDialog(){
		this.setState({"refreshDialog":false,"orderDialog":false});
		this.props.dispatch(actions.closeDialog());
	}
  render() {
		const tags = <ZhekouTags
						setTag={this.setTag.bind(this)}	
						curTag={this.state.tagName}
						search={this.state.search}
						searchResult={this.searchResult.bind(this)}
						/>
		const init = this.field.init;
		const formItemLayout = {
				labelCol: {fixedSpan: 6},
				wrapperCol: {fixedSpan: 30},
				};

		const date = new Date();
		const defaultNotice = date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日设置的折扣";
    return (
      <div className="page2-page">
	      <SystemDialog 
				 loginError={this.props.zhekou_limit_step1.loginError}
			    creating={this.props.zhekou_limit_step1.creating}
			    message={this.props.zhekou_limit_step1.message}
			    error={this.props.zhekou_limit_step1.error}
				 refreshDialog={this.state.refreshDialog}
				 orderDialog={this.state.orderDialog}
				 onCloseDialog={this.onCloseSystemDialog.bind(this)}
				/>
            
	      <Row style={{background:"#F6F6F6",margin:"3px 0"}} justify="start">
					<Col span="8" align="center">
						  <Breadcrumb maxNode={5}>
							  <Breadcrumb.Item>打折活动</Breadcrumb.Item>
							  <Breadcrumb.Item>创建</Breadcrumb.Item>
							  <Breadcrumb.Item>限购折扣</Breadcrumb.Item>
						  </Breadcrumb>
					</Col>
					<Col offset="2">
							<Step current={0} type="dot">
								<Step.Item title="设置活动" />
								<Step.Item title="选择商品" />
								<Step.Item title="完成"/>
							</Step>
					</Col>
			 </Row>
			 <Row justify="start" style={{marginTop:"50px"}}>
			   <Form direction="ver"  size="large" field={this.field}>
	            <Col span="21">
				  <FormItem label="折扣标签"  required {...formItemLayout}>
					<Search placeholder="选择标签"
						 type="normal"
						 {...init('tagName', {rules: [{validator:this.checkTag.bind(this)}]})}
						 combox={tags}
						 overlayVisible={this.state.overlayVisible}
						 onInputFocus={this.onVisibleChange.bind(this,true)}
						 hasIcon={false}
						 searchText="　"
						 autoWidth
						 className="tagSearch"
						 onSearch={()=>{}}
						 />
				  </FormItem>
				  <FormItem
						label="时间设置"
						{...formItemLayout}>
						<Row>
	                  <FormItem required label="开始"><DatePicker size="large" {...init('startTime',{rules: [{required: true,message:"请设置开始时间"}]})} showTime/></FormItem>
							<FormItem required label="结束"><DatePicker size="large" {...init('endTime',{rules: [{validator:this.checkEndDate.bind(this)}]})} showTime/></FormItem>
	               </Row>
				  </FormItem>
				  <FormItem
						label="活动备注"
						required 
						{...formItemLayout}>
						<Input size="large" className="notice" placeholder="备注" {...init('notice', {
									initValue:defaultNotice,
									rules: [
	                                {required: true,whitespace:true, message: '真的不打算写点什么吗？'},
									],
								})}  />
				  </FormItem>
				  <FormItem
						label=""
						{...formItemLayout}>
							<Link to="home">
								<Button  size="large" type="normal">
									<span>取消创建</span>
								</Button>
							</Link>
							<Button htmlType="submit" onClick={this.handleSubmit.bind(this)} style={{marginLeft:"20px"}} size="large" type="primary">
								创建活动
							</Button>
				  </FormItem>
				</Col>
			   </Form>
	          </Row>
	    </div>
    );
  }
}

export default connect((state)=> {
  return {
    zhekou_limit_step1: state.zhekou_limit_step1
  };
})(ZhekouLimitStep1);
